#!/usr/bin/php -q
<?php
	/*
	// File:	dump-0.5.php
	// Purpose:	Dumping an existing web-cp 0.5 database to a file
	// Creation:	2007-03-30
	// Author:	Gyrbo <dennis@gyrbo.be>
	*/

/*
 * Put this file into your web-cp 0.5 root folder and run it from the commandline
 */

chdir(dirname(__FILE__));

// Basic initialization
require_once('web/functions.inc.phps');
require_once('web/config.inc.php');

mysql_connect($cfg['dbhost'], $cfg['dbuser'], $cfg['dbpass']);
mysql_select_db($cfg['dbname']);


$fp = fopen('webcp-upgrade.dump', 'wb');
fwrite($fp, '# dump from web-cp '.$cfg['webcp']."\n");

function serialize_if_array(&$item) {
	if(is_array($item))
		$item = serialize($item);
}

$res = mysql_query('SELECT id FROM resellers');

if(mysql_num_rows($res)>0) {
	list($id) = mysql_fetch_row($res);
	$data = fetchdata('*', 'reseller', $id);
	$header = array_keys($data);

	fwrite($fp, '[resellers]'."\n");
	fputcsv($fp, $header);
	for(;;) {
		array_walk($data, 'serialize_if_array');
		fputcsv($fp, $data);
		$row = mysql_fetch_row($res);
		if(!$row)
			break;
		list($id) = $row;
		$data = fetchdata('*', 'reseller', $id);
	}
	fwrite($fp, "\n");
}


$res = mysql_query('SELECT id FROM domains');

if(mysql_num_rows($res)>0) {
	list($id) = mysql_fetch_row($res);
	$data = fetchdata('*', 'domain', $id);
	$header = array_keys($data);

	fwrite($fp, '[domains]'."\n");
	fputcsv($fp, $header);
	for(;;) {
		array_walk($data, 'serialize_if_array');
		fputcsv($fp, $data);
		$row = mysql_fetch_row($res);
		if(!$row)
			break;
		list($id) = $row;
		$data = fetchdata('*', 'domain', $id);
	}
	fwrite($fp, "\n");
}


$res = mysql_query('SELECT username FROM users');

if(mysql_num_rows($res)>0) {
	list($id) = mysql_fetch_row($res);
	$data = fetchdata('*', 'user', $id);
	$header = array_keys($data);

	fwrite($fp, '[users]'."\n");
	fputcsv($fp, $header);
	for(;;) {
		array_walk($data, 'serialize_if_array');
		fputcsv($fp, $data);
		$row = mysql_fetch_row($res);
		if(!$row)
			break;
		list($id) = $row;
		$data = fetchdata('*', 'user', $id);
	}
	fwrite($fp, "\n");
}



$res = mysql_query('SELECT * FROM mailman');

if(mysql_num_rows($res)>0) {
	$data = mysql_fetch_assoc($res);
	$header = array_keys($data);

	fwrite($fp, '[mailman]'."\n");
	fputcsv($fp, $header);
	for(;;) {
		fputcsv($fp, $data);
		$data = mysql_fetch_row($res);
		if(!$data)
			break;
	}
	fwrite($fp, "\n");
}

?>